package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cskaoyan.wordmemorize.converter.AdminLogConverter;
import com.cskaoyan.wordmemorize.dao.entity.OperateLogDO;
import com.cskaoyan.wordmemorize.dao.mapper.OperateLogMapper;
import com.cskaoyan.wordmemorize.dto.admin.OperateLogDTO;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.request.OperateLogPageRequest;
import com.cskaoyan.wordmemorize.service.AdminLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 管理员操作日志服务实现类
 */
@Service
public class AdminLogServiceImpl extends ServiceImpl<OperateLogMapper, OperateLogDO> implements AdminLogService {

    @Autowired
    private AdminLogConverter adminLogConverter;

    /**
     * 分页查询系统操作日志(后台操作日志)
     *
     * @param request 查询请求参数
     * @return 分页结果
     */
    @Override
    public PageDTO<OperateLogDTO> getOperateLogPage(OperateLogPageRequest request) {
        // 构建分页对象的默认参数，默认从第一页开始，每页显示10条记录
        int pageNum = request.getPageNum() != null ? request.getPageNum() : 1;
        int count = request.getCount() != null ? request.getCount() : 10;

        // 构建分页对象
        Page<OperateLogDO> page = new Page<>(pageNum, count);

        // 构建查询条件
        LambdaQueryWrapper<OperateLogDO> queryWrapper = new LambdaQueryWrapper<>();

        // 如果有员工ID，按员工ID查询
        if (StringUtils.hasText(request.getEmployeeId())) {
            queryWrapper.eq(OperateLogDO::getEmployeeId, Long.parseLong(request.getEmployeeId()));
        }

        // 如果有数据类型，按数据类型查询
        if (StringUtils.hasText(request.getDataType())) {
            queryWrapper.eq(OperateLogDO::getDataType, request.getDataType());
        }

        // 按创建时间降序排序，最新的日志显示在前面
        queryWrapper.orderByDesc(OperateLogDO::getCreateTime);

        // 执行分页查询
        Page<OperateLogDO> resultPage = page(page, queryWrapper);

        // 转换为DTO并返回
        return adminLogConverter.operationLogPage2PageDTO(resultPage.getRecords(), resultPage.getTotal());
    }

    /**
     * 保存操作日志
     *
     * @param operateLogDO 操作日志实体
     */
    @Override
    public void saveOperateLog(OperateLogDO operateLogDO) {
        save(operateLogDO);
    }
}
